package com.restybuddy.recommender.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;

import org.apache.log4j.Logger;

/**
 * @author qin
 *
 */
public class Config {
	   public static String CONFIGFILE = Config.class.getResource("/application.ini").getFile();
	    static Logger log = Logger.getLogger(Config.class);
	  
		public static  HashMap<String, LinkedHashMap<String, String>> readFile() {
	        
	        HashMap<String, LinkedHashMap<String, String>> v1 = new HashMap<String, LinkedHashMap<String, String>>();
	        LinkedHashMap<String, String> v2 = new LinkedHashMap<String, String>();
	        File file = new File(CONFIGFILE);
	        FileReader reader;
			try {
				reader = new FileReader(file);
				BufferedReader br = new BufferedReader(reader);
				
				String str = null;
		        String key = null;
				while ((str = br.readLine()) != null) {
					str = str.trim();
					
					if (str.indexOf("=") == -1
		                    && (str.indexOf("[") == -1 && str.indexOf("]") == -1)) {
		                continue;
		            }

		            if (str.indexOf("[") != -1 && str.indexOf("]") != -1) {
		                key = str.replace("[", "").replace("]", "");
		            }

		            if (key == null) {
		                continue;
		            }

		            String[] strs = null;
		            int index = str.indexOf("=");
		            if (index != -1) {
		            	strs = str.split("=");
		            	if(strs == null || strs.length != 2){
	                        continue;
	                    }
		            	v2.put(strs[0].trim(), strs[1].trim());
		                v1.put(key, v2);
		            }
		            
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
                log.error("Error  while parsing file , file'name is " + file.getName());
                log.error(e.getMessage());
			}
			return v1;
		}
		
		public static LinkedHashMap<String, String> getValue(String key) {
			HashMap<String, LinkedHashMap<String, String>> v1 = Config.readFile();
			LinkedHashMap<String, String> linkedHashMap = v1.get(key);
			return linkedHashMap;
		}
		
		public static String getValue(String key1 , String key2) {
			HashMap<String, LinkedHashMap<String, String>> v1 = Config.readFile();
			LinkedHashMap<String, String> keySet1 = v1.get(key1);
			String value = keySet1.get(key2);
			return value;
		}
		

}
